package com.gitee.srurl.core.util.redis;

import com.gitee.srurl.core.util.SpringContextUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @author zxw
 * @date 2023/4/30 11:22
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public abstract class RedisLockUtil {

    private static final RedissonClient redissonClient = SpringContextUtil.getBean(RedissonClient.class);

    public static boolean lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return true;
    }

    public static boolean tryLock(String lockKey, long timeout, TimeUnit timeUnit) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(timeout, timeUnit);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return lock.isHeldByCurrentThread();
        }
    }

    public static boolean tryLock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        return lock.tryLock();
    }

    public static boolean unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        if (lock.isHeldByCurrentThread()) {
            try {
                lock.unlock();
                return true;
            } catch (Exception e) {
                log.error("是否锁失败:", e);
                return false;
            }
        } else {
            return false;
        }
    }
}
